package com.example.testasm;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by 周楷桐 on 2021/12/26.
 * Description: 
 */
public class TestASM {

    public void test1() {
        try {

            File file = new File("/Users/macbook/Documents/ASMDemo/app/build/intermediates/javac/debug/classes/com/thunder/asmdemo/zxm31/Printer.class");

            FileInputStream fis          = new FileInputStream(file);
            ClassReader     classReader  = new ClassReader(fis);
            ClassWriter     classWriter  = new ClassWriter(classReader, ClassWriter.COMPUTE_MAXS);
            ClassVisitor    classVisitor = new TimeClassVisitor(Opcodes.ASM7, classWriter);
            classReader.accept(classVisitor, ClassReader.EXPAND_FRAMES);
            byte[]           code = classWriter.toByteArray();
            FileOutputStream fos  = new FileOutputStream(file);
            fos.write(code);
            fos.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        b();
    }

    private static void b() {
        // INVOKESTATIC java/lang/System.currentTimeMillis ()J
        // LSTORE 0
        long s = System.currentTimeMillis();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // INVOKESTATIC java/lang/System.currentTimeMillis ()J
        // LSTORE 2
        long e = System.currentTimeMillis();

        // GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
        // NEW java/lang/StringBuilder
        // DUP
        // INVOKESPECIAL java/lang/StringBuilder.<init> ()V
        // LDC "executed time : "
        // INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
        // LLOAD 2
        // LLOAD 0
        // LSUB
        // INVOKEVIRTUAL java/lang/StringBuilder.append (J)Ljava/lang/StringBuilder;
        // LDC " :ms"
        // INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
        // INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;
        // INVOKEVIRTUAL java/io/ PrintStream.println (Ljava/lang/String;)V
        System.out.println("executed time : " + (e - s) + " :ms");

    }

}
